package com.loe.test

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.fragment.app.Fragment
import java.lang.Exception
import java.lang.reflect.Field
import java.util.HashMap
import kotlin.reflect.KClass

/**
 * 路由
 */
object LoeRouter
{
    val classMap = HashMap<String, Class<*>>()
    val pathMap = HashMap<Class<*>, String>()

    fun addRouter(buildRouter: KClass<*>)
    {
        addRouter(buildRouter.java)
    }

    fun addRouter(buildRouter: Class<*>)
    {
        try
        {
            val field1: Field = buildRouter.getDeclaredField("classMap")
            classMap.putAll((field1.get(null) as HashMap<String, Class<*>>))
            val field2: Field = buildRouter.getDeclaredField("pathMap")
            pathMap.putAll((field2.get(null) as HashMap<Class<*>, String>))
        } catch (e: Exception)
        {
            Log.e("runtime", "LoeRouter赋值出错，请在主模块build.gradle添加：\ndependencies {\n    kapt 'com.gitee.LoeZhang:router:latest.release'\n}")
            e.printStackTrace()
        }
    }

    fun clear()
    {
        classMap.clear()
        pathMap.clear()
    }

    fun bind(cls: Class<*>, path: String)
    {
        classMap[path] = cls
        pathMap[cls] = path
    }

    fun getActivity(path: String): Class<Activity>
    {
        return classMap[path] as Class<Activity>
    }

    fun getFragment(path: String): Class<Fragment>
    {
        return classMap[path] as Class<Fragment>
    }

    fun getClass(path: String): Class<*>
    {
        return classMap[path]!!
    }

    fun getPath(cls: Class<*>): String
    {
        val path = pathMap[cls]
        return path ?: ""
    }
}